﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace Personal_Cloud_Disk_PC_Client
{
    class ClientWatcher
    {
        //声明要监视的目录
        private string watchPath = "D:\\watch";

        //变化处理事件监视器
        private FileSystemWatcher watcher;

        //记录任务队列
        private EventMonitor monitor;

        public ClientWatcher(EventMonitor monitor)
        {
            this.monitor = monitor;
        }


        void Watcher_Error(object sender, ErrorEventArgs e)
        {
            Logger.write("错误：" + e.ToString());
        }

        void Watcher_Deleted(object sender, FileSystemEventArgs e)
        {

            Logger.write(e.ChangeType + ":" + e.FullPath);
            this.monitor.raiseEvent(new CloudEvent(
                CloudEvent.Side.Client, CloudEvent.Entity.File, CloudEvent.Action.Delete, e.FullPath));
        }

        void Watcher_Created(object sender, FileSystemEventArgs e)
        {
            Logger.write(e.ChangeType + ":" + e.FullPath);
            this.monitor.raiseEvent(new CloudEvent(
                CloudEvent.Side.Client, CloudEvent.Entity.File, CloudEvent.Action.Create, e.FullPath));
        }

        void Watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Logger.write(e.ChangeType + ":" + e.FullPath);
            this.monitor.raiseEvent(new CloudEvent(
                CloudEvent.Side.Client, CloudEvent.Entity.File, CloudEvent.Action.Change, e.FullPath));
        }

        public void start()
        {
            Logger.write("client watcher starting");
            //添加文件变化处理事件
            if (watcher == null) {
                watcher = new FileSystemWatcher(watchPath, "*.*");

                //添加文件变更处理事件
                watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
                //添加文件创建处理事件
                watcher.Created += new FileSystemEventHandler(Watcher_Created);
                //添加文件删除处理事件
                watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
                //添加错误处理
                watcher.Error += new ErrorEventHandler(Watcher_Error);
            }

            //启动监视
            watcher.EnableRaisingEvents = true;
        }

        public void stop()
        {
            Logger.write("client watcher ending");
            if (watcher == null) {
                return;
            }
            //停止监视
            watcher.EnableRaisingEvents = false;
        }

    }

}
